from django.shortcuts import render

# Create your views here.
import json

from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view

from enterprise_sys.models import Enterprise, Enterprise_Usr, Employee_info
from activity_sys.models import *
from follow_sys.models import Follow_user
from utils.response_utils import *
from utils.session_utils import *

from utils.time_utils import *
from enterprise_sys.views import notice


@csrf_exempt
def post(request):
    if request.method != 'POST':
        return method_disallowed_response(request.method, 'POST')
    if has_login(request):
        user: User = get_login_user(request)
    else:
        return build_response(errno=2001, msg='用户未登录')
    data = json.loads(request.body)
    content = data.get('content')
    image_key_list = data.get('imageKey')
    is_share = data.get('isShared')
    share_id = data.get('shareId')
    time = get_now_time()

    if is_share:
        query = Activity.objects.filter(id=share_id)
        if query.count() == 0:
            return build_response(msg="该条动态不存在", errno=58983)
        share_count = query[0].share_count
        query.update(share_count=share_count + 1)
        new_activity = Activity.objects.create(
            user=user,
            time=time,
            content=content,
            is_share=is_share,
            share_id=share_id
        )
    else:
        new_activity = Activity.objects.create(user=user, time=time, content=content, is_share=is_share)
    activity_id = new_activity.id
    if image_key_list is not None:
        if len(image_key_list) > 9:
            return build_response(errno=58983, msg="图片数量过多(>9)")
        for image_key in image_key_list:
            ActivityImage.objects.create(image_key=image_key, belong_activity_id=activity_id)
    other_info = {
        "success": True,
        "postId": activity_id
    }
    return build_response(other_info=other_info, msg='动态发表成功')
    pass


@csrf_exempt
def send_comment(request):
    if request.method != 'POST':
        return method_disallowed_response(request.method, 'POST')
    if has_login(request):
        user: User = get_login_user(request)
    else:
        return build_response(errno=2001, msg='用户未登录')
    data = get_json_data(request)
    activity_id = data.get('postId')
    query = Activity.objects.filter(id=activity_id)
    if query.count() == 0:
        return build_response(errno=58983, msg='该动态不存在')
    activity_instance = query[0]
    content = data.get('content')
    time = get_now_time()
    new_comment = Comment.objects.create(user=user, time=time, content=content, belong_activity_id=activity_id)
    activity_instance.comment_count += 1
    activity_instance.save()
    msg = user.name + "评论了你"
    if user.id != activity_instance.user.id:
        notice(3, activity_instance.user.id, msg)
    return build_response(other_info={
        "cId": new_comment.id,
        "success": True
    }, msg='评论成功')


@csrf_exempt
def get_comments(request):
    if request.method != 'GET':
        return method_disallowed_response(request.method, 'GET')
    if has_login(request):
        user: User = get_login_user(request)
    else:
        return build_response(errno=2001, msg='用户未登录')
    data = request.GET
    activity_id = data.get('postId')
    query = Activity.objects.filter(id=activity_id)
    if query.count() == 0:
        return build_response(errno=58983, msg='该动态不存在')

    count = data.get('count')
    comment_list = []
    comments = Comment.objects.filter(belong_activity_id=activity_id).order_by('-time')
    if count is None:  # 为空则传全部评论
        for comment in comments:
            comment_list.append(comment.parse_dict())
    else:
        for i in range(min(comments.count(), int(count))):
            comment = comments[i]
            comment_list.append(comment.parse_dict())
    other_info = {
        "success": True,
        "comments": comment_list
    }
    return build_response(other_info=other_info, msg="获取评论列表成功")


@csrf_exempt
def delete_post(request):
    if request.method != 'POST':
        return method_disallowed_response(request.method, 'POST')
    if has_login(request):
        user: User = get_login_user(request)
    else:
        return build_response(errno=2001, msg='用户未登录')
    data = get_json_data(request)
    activity_id = data.get('postId')
    query = Activity.objects.filter(id=activity_id)
    if query.count() == 0:
        return build_response(errno=58983, msg='该动态不存在')
    activity_instance = query[0]
    if activity_instance.user.id != user.id:
        return build_response(errno=58983, msg="非该条动态所有者")
    if activity_instance.is_delete:
        return build_response(errno=58983, msg="该动态已经被删除")
    activity_instance.is_delete = True
    activity_instance.save()
    return build_response(msg='删除成功')


@csrf_exempt
def get_post(request):
    if request.method != 'GET':
        return method_disallowed_response(request.method, 'GET')
    if not has_login(request):
        return build_response(errno=2001, msg='用户未登录')
    data = request.GET
    activity_id = data.get('postId')
    query = Activity.objects.filter(id=activity_id)
    if query.count() == 0:
        return build_response(errno=58983, msg='该动态不存在')
    activity_instance = query[0]
    activity_info = activity_instance.parse_dict()
    image_key_list = []
    for image_key in ActivityImage.objects.filter(belong_activity_id=activity_id):
        image_key_list.append(image_key.image_key)
    activity_info['imgKey'] = image_key_list
    activity_info['success'] = True
    return build_response(other_info={
        "post": activity_info
    }, msg="获取动态成功")


@csrf_exempt
@api_view(['PUT'])
def like(request):
    if request.method != 'PUT':
        return method_disallowed_response(request.method, 'PUT')
    if has_login(request):
        user: User = get_login_user(request)
    else:
        return build_response(errno=2001, msg='用户未登录')
    activity_id = request.data.get('postId')
    query = Activity.objects.filter(id=activity_id)
    if query.count() == 0:
        return build_response(errno=58983, msg='该动态不存在')
    if Like.objects.filter(user_id=user.id, belong_activity_id=activity_id).count() != 0:
        return build_response(errno=2001, msg="已经点过赞了")
    new_like = Like.objects.create(user=user, time=get_now_time(), belong_activity_id=activity_id)
    like_count = query[0].like_count
    query.update(like_count=like_count + 1)
    if user.id != query[0].user_id:
        notice(3, query[0].user_id, "收到了赞")
    return build_response(other_info={
        "success": True,
        "lId": new_like.id
    }, msg="点赞成功")


@csrf_exempt
def get_post_list(request):
    if request.method != 'GET':
        return method_disallowed_response(request.method, 'GET')
    if not has_login(request):
        return build_response(errno=2001, msg='用户未登录')
    user_id = request.GET.get('userId')
    return_info = {'success': True}
    user_activity_list = Activity.objects.filter(user_id=user_id).order_by("-time")
    postList = []
    for activity in user_activity_list:
        info_dict = activity.parse_dict()
        image_key_list = []
        comments = []
        query_comments = Comment.objects.filter(belong_activity_id=activity.id).order_by('-time')
        if query_comments.count() >= 3:
            # print(query_comments.count())
            for i in range(3):
                comments.append(query_comments[i].parse_dict())
        else:
            for comment in query_comments:
                comments.append(comment.parse_dict())
        for image_key in ActivityImage.objects.filter(belong_activity_id=activity.id):
            image_key_list.append(image_key.image_key)
        info_dict['imgKey'] = image_key_list
        info_dict['comments'] = comments
        postList.append(info_dict)
    return_info["postList"] = postList
    return build_response(other_info=return_info, msg="获取动态列表成功")


@csrf_exempt
def get_enterprise_post_list(request):
    if request.method != 'GET':
        return method_disallowed_response(request.method, 'GET')
    if not has_login(request):
        return build_response(errno=2001, msg='用户未登录')
    enterprise_id = request.GET.get('enterpriseId')
    return_info = {'success': True}
    user_list = []

    for item in Enterprise_Usr.objects.filter(enterprise_id=enterprise_id):
        user_list.append(item.usr_id)
    # print(user_list)
    user_activity_list = Activity.objects.filter(user_id__in=user_list).order_by("-time")
    postList = []
    for activity in user_activity_list:
        info_dict = activity.parse_dict()
        image_key_list = []
        comments = []
        query_comments = Comment.objects.filter(belong_activity_id=activity.id).order_by('-time')
        if query_comments.count() >= 3:
            # print(query_comments.count())
            for i in range(3):
                comments.append(query_comments[i].parse_dict())
        else:
            for comment in query_comments:
                comments.append(comment.parse_dict())
        for image_key in ActivityImage.objects.filter(belong_activity_id=activity.id):
            image_key_list.append(image_key.image_key)
        info_dict['imgKey'] = image_key_list
        info_dict['comments'] = comments
        postList.append(info_dict)
    return_info["postList"] = postList
    return build_response(other_info=return_info, msg="获取动态列表成功")


@csrf_exempt
def count_follow(request):
    if request.method != 'GET':
        return method_disallowed_response(request.method, 'GET')
    if has_login(request):
        user: User = get_login_user(request)
    else:
        return build_response(errno=2001, msg='用户未登录')
    user_id = request.GET.get('userId')
    user1 = User.objects.filter(id=user_id)
    count_follows = Follow_user.objects.filter(followee_user_id=user_id)#fans
    count_followee = Follow_user.objects.filter(follower_id=user_id)#关注数
    post = Activity.objects.filter(user_id=user_id,is_delete=False)
    return build_response({
        "code":200,
        "userName": user1[0].name,
        "count_follows": count_follows.count(),
        "count_followee": count_followee.count(),
        "count_post": post.count()
    })
